package com.haitaoit.chengquan.module.near;

import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.github.dialog.ActionSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.baiduservice.LocationService;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.module.home.activity.maintenance.MaintenanceDetailActivity2;
import com.haitaoit.chengquan.module.home.activity.maintenance.SeachDemandActivity;
import com.haitaoit.chengquan.module.home.adapter.forum.ForumDownAdapter;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.module.near.adapter.MaplistAdapter;
import com.haitaoit.chengquan.module.near.model.NearServerModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyGridView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.squareup.leakcanary.RefWatcher;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.haitaoit.chengquan.R.id.need_popupwind_three;

/**
 * Created by Administrator on 2016/9/22.
 */
public class NearFragment extends Fragment {
    @ViewInject(R.id.et_map_search)
    EditText     et_map_search;
    @ViewInject(R.id.map_order)
    ImageView    map_order;
    @ViewInject(R.id.near_zonghe)
    TextView     near_zonghe;
    @ViewInject(R.id.near_leixing_all)
    LinearLayout nearZongHeAll;
    @ViewInject(R.id.near_leixing)
    TextView     near_leixing;
    @ViewInject(R.id.near_leixing_img)
    ImageView    near_leixing_img;
    @ViewInject(R.id.near_diqu)
    TextView     near_diqu;
    @ViewInject(R.id.near_diqu_img)
    ImageView    near_diqu_img;
    @ViewInject(R.id.near_price)
    TextView     near_price;
    @ViewInject(R.id.near_xuqiu_ll)
    LinearLayout near_xuqiu_ll;
    @ViewInject(R.id.near_fuwu_ll)
    LinearLayout near_fuwu_ll;
    @ViewInject(R.id.fuwu_leixing_all)
    LinearLayout fuwu_leixing_all;

    @ViewInject(R.id.near_all)
    TextView    near_all;
    @ViewInject(R.id.near_leixing2)
    TextView    near_leixing2;
    @ViewInject(R.id.near_leixing_img2)
    ImageView   near_leixing_img2;
    @ViewInject(R.id.near_xinyu)
    TextView    near_xinyu;
    @ViewInject(R.id.near_xinyu_img)
    ImageView   near_xinyu_img;
    @ViewInject(R.id.mapView)
    MapView     mapView;
    @ViewInject(R.id.mapList)
    ListView    mapList;
    @ViewInject(R.id.near_rb1)
    RadioButton near_rb1;
    @ViewInject(R.id.near_rb2)
    RadioButton near_rb2;
    @ViewInject(R.id.progressbara)
    ProgressBar progressbara;

    // 分类列表
    List<TitleModel> need_list = new ArrayList<>();
    BaiduMap           mBaiduMap;
    LocationService    locationService;
    BDLocationListener mListener;

    boolean isToast = true;
    private String Top_type           = "1";//1 附近需求  2 附近服务商
    private int    order_type         = 0;//需求商0距离排序，1价格排序
    private int    service_order_type = 0;//服务商0距离排序，1价格排序
    private String categoryId         = "0";
    private String serverTypeId       = "0";
    private double latitude           = 39.915174;
    private double longitude          = 121.446496;

    private PopupWindow myPopWindow;
    private PopupWindow myAllPopWindow;
    private int SelectIndex = 0, type = 1;
    private int ServerIndex = 0;
    private int mapIndex    = -1;
    private OverlayOptions mOption;
    private View           mV;
    private LinearLayout   mNeedPopupwind;
    int fiset = 1;
    private int swuch   = 1;
    private int umnberP = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        SDKInitializer.initialize(getActivity().getApplicationContext());
        mV = inflater.inflate(R.layout.fragment_near, null);
        ViewUtils.inject(this, mV);


        mBaiduMap = mapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (isToast) {
                    isToast = false;
                    if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                        MapStatusUpdate u1 = MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(11).build());
                        mBaiduMap.setMapStatus(u);
                        mBaiduMap.setMapStatus(u1);
                    }
                    if (!("").equals(location.getCity())) {
                        if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                            ToastUtils.showToast("定位成功");
                        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                            ToastUtils.showToast("网络定位成功");
                        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                            ToastUtils.showToast("定位成功");
                        } else if (location.getLocType() == BDLocation.TypeServerError) {
                            ToastUtils.showToast("定位失败");
                        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                            ToastUtils.showToast("定位失败,请检查网络是否通畅");
                        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                            ToastUtils.showToast("定位失败");
                        }
                        ToastUtils.showToast("定位城市:" + location.getCity());
                        //保存起来，以供home页面来定位
                        PreferenceUtils.setPrefString("location_city", location.getCity());
                        if (location.getCity() != null && !location.getCity().equals("")) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                        addMyIcon(latitude, longitude);
                        //获取到定位数据之后才能才能去附近的数据
                        //请求
                        if (Top_type.equals("1")) {
                            swuch = 1;
                            httpGetNearDemand();
                            near_rb1.setEnabled(false);
                            near_rb2.setEnabled(true);
                        } else {
                            swuch = 2;
                            httpGetNearServer();
                            near_rb1.setEnabled(true);
                            near_rb2.setEnabled(false);
                        }
                        fiset++;
                    }
                }
            }

        };
        locationService = new LocationService(getActivity());
        locationService.registerListener(mListener);
        Vibrator mVibrator = (Vibrator) getActivity()
                .getSystemService(Service.VIBRATOR_SERVICE);
        locationService.start();// 定位SDK

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                if (mapIndex == marker.getZIndex()) {
                    mBaiduMap.hideInfoWindow();
                    mapIndex = -1;
                } else {
                    mapIndex = marker.getZIndex();
                    LatLng point1 = marker.getPosition();
                    // 创建InfoWindow展示的view
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.textview, null);
                    TextView button = (TextView) view.findViewById(R.id.text);
                    button.setBackgroundResource(R.color.map_color);
                    if (marker.getZIndex() == Integer.MAX_VALUE) {
                        button.setText("我的位置");
                    } else {
                        if (Top_type.equals("1")) {
                            button.setText(nearList.get(marker.getZIndex()).getName() + "\n参考价格：￥" + nearList.get(marker.getZIndex()).getReference_price());
                        } else {
                            button.setText(nearList.get(marker.getZIndex()).getName() + "\n信誉：" + nearList.get(marker.getZIndex()).getScore() + "分");
                        }
                    }
                    button.setGravity(Gravity.CENTER);
                    button.setTextSize(12);
                    button.setTextColor(Color.WHITE);
                    // 定义用于显示该InfoWindow的坐标点
                    // 创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
                    InfoWindow mInfoWindow = new InfoWindow(view, point1, -100);
                    // 显示InfoWindow
                    mBaiduMap.showInfoWindow(mInfoWindow);

                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e("tag", marker.getZIndex() + "====");
                            if (!(marker.getZIndex() == Integer.MAX_VALUE)) {
                                Intent intent = new Intent();
                                if (Top_type.equals("1")) {//需求详情
                                    intent.setClass(getActivity(), SeachDemandActivity.class);
                                    intent.putExtra("id", nearList.get(marker.getZIndex()).getId());
                                    startActivity(intent);
                                } else {//服务详情
                                    intent.setClass(getActivity(), MaintenanceDetailActivity2.class);
                                    intent.putExtra("id", nearList.get(marker.getZIndex()).getId());
                                    startActivity(intent);
                                }
                            }
                        }
                    });
                }
                return false;
            }
        });

        return mV;
    }


    @Override
    public void onResume() {
        super.onResume();
        locationService.start();// 定位SDK

        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(new LatLng(latitude, longitude));
        //请求
        if (Top_type.equals("1") && fiset != 1) {
            swuch = 1;
            httpGetNearDemand();
            near_rb1.setEnabled(false);
            near_rb2.setEnabled(true);
        } else {
            swuch = 2;
            httpGetNearServer();
            near_rb1.setEnabled(true);
            near_rb2.setEnabled(false);
        }

        if (mBaiduMap != null) {
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }

    @Override
    public void onPause() {
        if (mNeedPopupwind != null) {
            mNeedPopupwind.setVisibility(View.GONE);
        } else {

            super.onPause();
        }

        locationService.stop();
        //        mapView.onDestroy();
        mBaiduMap.setMyLocationEnabled(false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        et_map_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("1".equals(Top_type)) {//附近需求
                    httpGetNearDemand(s.toString());
                } else {//附近服务
                    httpGetNearServer1(s.toString());
                }
            }
        });
    }


    //标注当前位置
    private void addMyIcon(double laitude, double longitude) {
        ExitApplication.latitude = laitude;
        ExitApplication.longitude = longitude;
        LatLng point = new LatLng(laitude, longitude);
        // 构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.pic_tra);
        // 构建MarkerOption，用于在地图上添加Marker
        mOption = new MarkerOptions().position(point).icon(bitmap);
        // 在地图上添加Marker，并显示
        Marker marker = (Marker) mBaiduMap.addOverlay(mOption);
        marker.setZIndex(Integer.MAX_VALUE);
    }

    @OnClick({R.id.near_rb1, R.id.near_rb2, R.id.near_leixing_all, R.id.near_leixing_LL,
            R.id.near_diqu_LL, R.id.near_price, R.id.fuwu_leixing_all, R.id.near_leixing_LL2,
            R.id.near_xinyu_LL, R.id.map_order})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.map_order:
                if ("1".equals(Top_type)) {
                    showDialog(true);
                } else {
                    showDialog(false);
                }
                break;
            case R.id.near_rb1:
                swuch = 1;
                //附近需求商
                et_map_search.setText("");
                Top_type = "1";
                near_xuqiu_ll.setVisibility(View.VISIBLE);
                near_fuwu_ll.setVisibility(View.GONE);

                httpGetNearDemand();
                if (swuch == 1) {
                    near_rb1.setEnabled(false);
                    near_rb2.setEnabled(true);
                    return;
                }
                //                mBaiduMap.clear();
                //                locationService.registerListener(mListener);
                //                locationService.start();// 定位SDK
                break;
            case R.id.near_rb2:
                //附近服务商
                swuch = 2;

                et_map_search.setText("");
                near_xuqiu_ll.setVisibility(View.GONE);
                near_fuwu_ll.setVisibility(View.VISIBLE);
                Top_type = "2";

                httpGetNearServer();
                if (swuch == 2) {
                    near_rb2.setEnabled(false);
                    near_rb1.setEnabled(true);
                    return;
                }
                //                mBaiduMap.clear();
                //                locationService.registerListener(mListener);
                //                locationService.start();// 定位SDK
                break;
            case R.id.near_leixing_LL:// 第一个类型
                setColor1();
                near_leixing.setTextColor(getActivity().getResources().getColor(R.color.app_color));
                //需求分类列表
                if (need_list != null) {
                    need_list = new ArrayList<>();
                }
                if (need_list.size() != 0) {
                    need_list.clear();
                }
                httpGetdemand_class_list();
                break;
            //            case R.id.near_diqu_LL:// 地区
            //                setColor1();
            //                near_diqu.setTextColor(getActivity().getResources().getColor(R.color.app_color));
            //                break;
            //            case R.id.near_price:// 价格
            //                setColor1();
            //                near_price.setTextColor(getActivity().getResources().getColor(R.color.app_color));
            //                break;

            case R.id.near_leixing_all://第一个综合

                setColor1();
                near_zonghe.setTextColor(getActivity().getResources().getColor(R.color.app_color));
                categoryId = "0";

                iniPopupWindowAll();
                //需求列表请求
                httpGetNearDemand();
                myAllPopWindow.showAsDropDown(near_xuqiu_ll, 0, 0);
                break;
            case R.id.fuwu_leixing_all:// 第二个综合
                setColor2();
                near_all.setTextColor(getActivity().getResources().getColor(R.color.app_color));
                serverTypeId = "0";
                //服务列表请求
                httpGetNearServer();
                iniPopupWindowAll();
                myAllPopWindow.showAsDropDown(near_xuqiu_ll, 0, 0);
                break;
            case R.id.near_leixing_LL2:// 第二个类型
                setColor2();
                near_leixing2.setTextColor(getActivity().getResources().getColor(R.color.app_color));
                //服务分类列表
                if (need_list != null) {
                    need_list = new ArrayList<>();
                }
                if (need_list.size() != 0) {
                    need_list.clear();
                }
                need_list.add(new TitleModel("1", "个人商户"));
                need_list.add(new TitleModel("2", "企业商户"));
                iniPopupWindow();
                myPopWindow.showAsDropDown(near_fuwu_ll, 0, 0);
                break;
            //            case R.id.near_xinyu_LL:// 信誉
            //                setColor2();
            //                near_xinyu.setTextColor(getActivity().getResources().getColor(R.color.app_color));
            //                break;
        }
    }

    public void setColor1() {
        near_zonghe.setTextColor(getActivity().getResources().getColor(R.color.black_text));
        near_leixing.setTextColor(getActivity().getResources().getColor(R.color.black_text));
        near_diqu.setTextColor(getActivity().getResources().getColor(R.color.black_text));
        near_price.setTextColor(getActivity().getResources().getColor(R.color.black_text));
    }

    public void setColor2() {
        near_all.setTextColor(getActivity().getResources().getColor(R.color.black_text));
        near_leixing2.setTextColor(getActivity().getResources().getColor(R.color.black_text));
        near_xinyu.setTextColor(getActivity().getResources().getColor(R.color.black_text));
    }

    //TODO:这里需要进行接口对接，按距离排序
    private void iniPopupWindowAll() {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.forum_down_all_item, null);
        layout.findViewById(R.id.forum_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAllPopWindow.dismiss();
            }
        });


        final View first = layout.findViewById(R.id.first_image);
        final View second = layout.findViewById(R.id.second_image);
        final View thired = layout.findViewById(R.id.thired_image);
        first.setVisibility(View.INVISIBLE);
        second.setVisibility(View.INVISIBLE);
        thired.setVisibility(View.INVISIBLE);


        if (myAllPopWindow == null) {
            myAllPopWindow = new PopupWindow(layout);
            first.setVisibility(View.VISIBLE);
            second.setVisibility(View.INVISIBLE);
            thired.setVisibility(View.INVISIBLE);
            near_zonghe.setText("综合");
            near_all.setText("综合");
        }


        myAllPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
        // 控制popupwindow 的宽度和高度
        myAllPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        myAllPopWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);

        // 控制popupwindow 点击屏幕其他地方消失
        myAllPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
        myAllPopWindow.setOutsideTouchable(true);


        //点击综合的时候
        layout.findViewById(R.id.need_popupwind_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.equals(Top_type, "1")) {
                    near_zonghe.setText("综合");
                } else {
                    near_all.setText("综合");
                }
                myAllPopWindow.dismiss();

                first.setVisibility(View.VISIBLE);
                second.setVisibility(View.INVISIBLE);
                thired.setVisibility(View.INVISIBLE);


            }
        });
        //点击按距离排序的时候
        layout.findViewById(R.id.need_popupwind_second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(Top_type, "1")) {
                    near_zonghe.setText("距离");
                    order_type = 0;
                    initNeedData();
                } else {
                    near_all.setText("距离");
                    service_order_type = 0;
                    initProvideData();

                }
                myAllPopWindow.dismiss();
                first.setVisibility(View.INVISIBLE);
                second.setVisibility(View.VISIBLE);
                thired.setVisibility(View.INVISIBLE);

            }
        });
        //点击按价格排序的时候
        layout.findViewById(need_popupwind_three).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(Top_type, "1")) {
                    near_zonghe.setText("价格");
                    order_type = 1;
                    initNeedData();
                } else {
                    near_all.setText("价格");
                    service_order_type = 1;
                    initProvideData();
                }
                myAllPopWindow.dismiss();

                first.setVisibility(View.INVISIBLE);
                second.setVisibility(View.INVISIBLE);
                thired.setVisibility(View.VISIBLE);
            }
        });

    }

    //TODO：附近服务商的距离和价格
    private void initNeedData() {
        mBaiduMap.clear();
        addMyIcon(latitude, longitude);
        List<NameValuePairSign> pair = new ArrayList<>();
        pair.add(new NameValuePairSign("name", ""));
        pair.add(new NameValuePairSign("orderby", order_type + ""));
        pair.add(new NameValuePairSign("categoryid", categoryId));
        pair.add(new NameValuePairSign("longitude", longitude + ""));
        pair.add(new NameValuePairSign("latitude", latitude + ""));
        String sign = GetSign.genPackageSign(pair);


        RequestParams params = new RequestParams();
        params.addQueryStringParameter("categoryid", categoryId);
        params.addQueryStringParameter("longitude", longitude + "");
        params.addQueryStringParameter("latitude", latitude + "");
        params.addQueryStringParameter("name", "");
        params.addQueryStringParameter("orderby", order_type + "");
        params.addQueryStringParameter("sign", sign);
        progressbara.setVisibility(View.VISIBLE);
        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getnearby_demand_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mapView.clearDisappearingChildren();
                try {
                    JSONObject json = new JSONObject(responseInfo.result.toString());
                    String ErrCode = json.getString("ErrCode");
                    String ErrMsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    if (Integer.valueOf(ErrCode) == 0) {
                        //                        nearList = new ArrayList<NearServerModel>();
                        nearList = gson.fromJson(Response, new TypeToken<ArrayList<NearServerModel>>() {
                        }.getType());
                        addDemandIcon();

                    } else {
                        if (nearList == null) {
                            nearList = new ArrayList<NearServerModel>();
                        } else {
                            need_list.clear();
                        }
                        ToastUtils.showToast(ErrMsg);

                    }

                    setMapList(false);
                    progressbara.setVisibility(View.INVISIBLE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressbara.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                mapView.clearDisappearingChildren();
                ToastUtils.showToast("获取数据失败，请检查网络！");
                progressbara.setVisibility(View.INVISIBLE);
            }
        });

    }

    //TODO:附近需求商的距离和价格
    private void initProvideData() {
        mBaiduMap.clear();
        addMyIcon(latitude, longitude);
        List<NameValuePairSign> pair = new ArrayList<>();
        pair.add(new NameValuePairSign("type", serverTypeId));
        pair.add(new NameValuePairSign("longitude", longitude + ""));
        pair.add(new NameValuePairSign("latitude", latitude + ""));
        pair.add(new NameValuePairSign("name", ""));
        pair.add(new NameValuePairSign("orderby", service_order_type + ""));

        String sign = GetSign.genPackageSign(pair);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", serverTypeId);
        params.addQueryStringParameter("name", "");
        params.addQueryStringParameter("orderby", service_order_type + "");
        params.addQueryStringParameter("longitude", longitude + "");
        params.addQueryStringParameter("latitude", latitude + "");
        params.addQueryStringParameter("sign", sign);
        progressbara.setVisibility(View.VISIBLE);
        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getnearby_server_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject json = new JSONObject(responseInfo.result.toString());
                    String ErrCode = json.getString("ErrCode");
                    String ErrMsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    if (Integer.valueOf(ErrCode) == 0) {
                        //                        nearList = new ArrayList<NearServerModel>();

                        nearList = gson.fromJson(Response, new TypeToken<ArrayList<NearServerModel>>() {
                        }.getType());
                        addDemandIcon();

                    } else {
                        if (nearList == null) {
                            nearList = new ArrayList<NearServerModel>();
                        } else {
                            need_list.clear();
                        }
                        ToastUtils.showToast(ErrMsg);

                    }

                    setMapList(true);
                    progressbara.setVisibility(View.INVISIBLE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressbara.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showToast("获取数据失败，请检查网络！");
                progressbara.setVisibility(View.INVISIBLE);
            }
        });

    }

    // 弹出框
    private void iniPopupWindow() {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.forum_down_item, null);
        layout.findViewById(R.id.forum_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myPopWindow.dismiss();
            }
        });

        MyGridView forum_dwom_grid = (MyGridView) layout.findViewById(R.id.forum_dwom_grid);
        final ForumDownAdapter fdAdapter = new ForumDownAdapter(getActivity());

        if (Top_type.equals("1")) {
            fdAdapter.setIsIndex(SelectIndex);
        } else {
            fdAdapter.setIsIndex(ServerIndex);
        }
        fdAdapter.setList(need_list);
        fdAdapter.setBackCall(new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                int position = (Integer) obj[0];
                switch (which) {
                    case R.id.text:
                        //请求
                        if (Top_type.equals("1")) {
                            SelectIndex = position;
                            categoryId = fdAdapter.getList().get(position).getId();
                            fdAdapter.setIsIndex(SelectIndex);
                            fdAdapter.notifyDataSetChanged();

                            httpGetNearDemand();
                        } else {
                            ServerIndex = position;
                            serverTypeId = fdAdapter.getList().get(position).getId();
                            fdAdapter.setIsIndex(ServerIndex);
                            fdAdapter.notifyDataSetChanged();
                            httpGetNearServer();
                        }
                        break;
                }
                //对文字进行赋值操作
                if (TextUtils.equals(Top_type, "1")) {
                    near_leixing.setText(need_list.get(position).getName());
                } else {
                    near_leixing2.setText(need_list.get(position).getName());
                }
                myPopWindow.dismiss();
                super.deal(which, obj);
            }
        });

        if (need_list.size() >= 4) {
            forum_dwom_grid.setNumColumns(4);
            for (int i = 0; i < need_list.size(); i++) {
                if (need_list.get(i).getName().length() >= 6) {
                    forum_dwom_grid.setNumColumns(3);
                    break;
                }
            }
        }
        forum_dwom_grid.setAdapter(fdAdapter);

        myPopWindow = new PopupWindow(layout);
        myPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
        // 控制popupwindow 的宽度和高度
        myPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        myPopWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);

        // 控制popupwindow 点击屏幕其他地方消失
        myPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
        myPopWindow.setOutsideTouchable(true);
        // 触摸popupwindow外部,popupwindow消失,这个要求你的popupwindow要有背景图片才可以成功
    }

    List<NearServerModel> nearList;

    //获取附近需求
    private void httpGetNearDemand() {
        httpGetNearDemand("");
    }

    //获取附近需求
    private void httpGetNearDemand(String search) {
        mBaiduMap.clear();
        addMyIcon(latitude, longitude);
        List<NameValuePairSign> pair = new ArrayList<>();
        pair.add(new NameValuePairSign("name", search));
        pair.add(new NameValuePairSign("orderby", order_type + ""));
        pair.add(new NameValuePairSign("categoryid", categoryId));
        pair.add(new NameValuePairSign("longitude", longitude + ""));
        pair.add(new NameValuePairSign("latitude", latitude + ""));
        String sign = GetSign.genPackageSign(pair);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("categoryid", categoryId);
        params.addQueryStringParameter("longitude", longitude + "");
        params.addQueryStringParameter("latitude", latitude + "");
        params.addQueryStringParameter("name", search);
        params.addQueryStringParameter("orderby", order_type + "");
        params.addQueryStringParameter("sign", sign);
        progressbara.setVisibility(View.VISIBLE);
        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getnearby_demand_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mapView.clearDisappearingChildren();
                try {
                    JSONObject json = new JSONObject(responseInfo.result.toString());
                    String ErrCode = json.getString("ErrCode");
                    String ErrMsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    if (Integer.valueOf(ErrCode) == 0) {
                        //                        nearList = new ArrayList<NearServerModel>();
                        nearList = gson.fromJson(Response, new TypeToken<ArrayList<NearServerModel>>() {
                        }.getType());
                        addDemandIcon();

                    } else {
                        if (nearList == null) {
                            nearList = new ArrayList<NearServerModel>();
                        } else {
                            need_list.clear();
                        }
                        ToastUtils.showToast(ErrMsg);
                        if (umnberP == 1) {
                            httpGetNearDemand();
                            umnberP++;
                        }
                    }

                    //                    获取附近需求
                    if (swuch != 2) {
                        setMapList(false);
                    }

                    progressbara.setVisibility(View.INVISIBLE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressbara.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                mapView.clearDisappearingChildren();
                ToastUtils.showToast("获取数据失败，请检查网络！");
                progressbara.setVisibility(View.INVISIBLE);
            }
        });
    }

    public void showDialog(final boolean top_type) {
        new ActionSheetDialog(getActivity()).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("选择排序方式", "#666666", null)
                .addSheetItem("按距离排序", "#037BFF", new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int i) {
                        if (top_type) {
                            order_type = 0;
                            httpGetNearDemand();
                        } else {
                            service_order_type = 0;
                            httpGetNearServer();
                        }
                    }
                })
                .addSheetItem(top_type ? "按价格排序" : "按信誉排序", "#037BFF", new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int i) {
                        if (top_type) {
                            order_type = 1;
                            httpGetNearDemand();
                        } else {
                            service_order_type = 1;
                            httpGetNearServer();
                        }
                    }
                }).show();
    }
    //    List<NearServerModel> serverList;

    //获取附近服务商
    private void httpGetNearServer() {
        httpGetNearServer1("");
    }

    //                    获取附近服务商
    private void httpGetNearServer1(String search) {
        mBaiduMap.clear();
        addMyIcon(latitude, longitude);
        List<NameValuePairSign> pair = new ArrayList<>();
        pair.add(new NameValuePairSign("type", serverTypeId));
        pair.add(new NameValuePairSign("longitude", longitude + ""));
        pair.add(new NameValuePairSign("latitude", latitude + ""));
        pair.add(new NameValuePairSign("name", search));
        pair.add(new NameValuePairSign("orderby", service_order_type + ""));

        String sign = GetSign.genPackageSign(pair);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", serverTypeId);
        params.addQueryStringParameter("name", search);
        params.addQueryStringParameter("orderby", service_order_type + "");
        params.addQueryStringParameter("longitude", longitude + "");
        params.addQueryStringParameter("latitude", latitude + "");
        params.addQueryStringParameter("sign", sign);
        progressbara.setVisibility(View.VISIBLE);
        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getnearby_server_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject json = new JSONObject(responseInfo.result.toString());
                    String ErrCode = json.getString("ErrCode");
                    String ErrMsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    if (Integer.valueOf(ErrCode) == 0) {
                        //                        nearList = new ArrayList<NearServerModel>();

                        nearList = gson.fromJson(Response, new TypeToken<ArrayList<NearServerModel>>() {
                        }.getType());
                        addDemandIcon();
                    } else {
                        if (nearList == null) {
                            nearList = new ArrayList<NearServerModel>();
                        } else {
                            need_list.clear();
                        }
                        ToastUtils.showToast(ErrMsg);
                    }
                    //                    获取附近服务商
                    if (swuch != 1) {
                        setMapList(true);
                    }
                    progressbara.setVisibility(View.INVISIBLE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressbara.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showToast("获取数据失败，请检查网络！");
                progressbara.setVisibility(View.INVISIBLE);
            }
        });
    }

    //添加标注点位置
    public void addDemandIcon() {
        if (Top_type.equals("1")) {
            for (int i = 0; i < nearList.size(); i++) {
                LatLng point = new LatLng(nearList.get(i).getLatitude(), nearList.get(i).getLongitude());
                // 构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.pic42);
                // 构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                // 在地图上添加Marker，并显示
                Marker marker = (Marker) mBaiduMap.addOverlay(option);
                marker.setZIndex(i);
            }
        } else {
            for (int i = 0; i < nearList.size(); i++) {
                LatLng point = new LatLng(nearList.get(i).getLatitude(), nearList.get(i).getLongitude());
                // 构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.pic42);
                // 构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                // 在地图上添加Marker，并显示
                Marker marker = (Marker) mBaiduMap.addOverlay(option);
                marker.setZIndex(i);
            }
        }
    }


    private void httpGetdemand_class_list() {

        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        String url = "";
        if (Top_type.equals("1")) {
            url = Constant.Getdemand_class_list;
        } else {
            url = Constant.GetSerVer_Class_List;
        }

        HttpUtilsSingle.doGet(getActivity(), false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            need_list = gson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());

                            iniPopupWindow();
                            if (Top_type.equals("1")) {
                                myPopWindow.showAsDropDown(near_xuqiu_ll, 0, 0);
                            }
                            return;


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private MaplistAdapter maplistAdapter;

    /*ture服务商*/
    private void setMapList(boolean isService) {

        //        if (maplistAdapter == null) {
        maplistAdapter = new MaplistAdapter(getActivity());
        maplistAdapter.getDataList().addAll(nearList);
        maplistAdapter.setService(isService);
        mapList.setAdapter(maplistAdapter);
        //        } else {
        //            maplistAdapter.getDataList().clear();
        //            maplistAdapter.getDataList().addAll(nearList);
        //            maplistAdapter.setService(isService);
        //            maplistAdapter.notifyDataSetChanged();
        //        }

    }

    //主要用于检测内存泄漏
    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = ExitApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
